// pages/admin/addproduct/addproduct.js
import { ProductModel }  from "../../../models/productModel.js"
import { CategoryModel } from "../../../models/CategoryModel.js"
import { MyDate } from "../../../models/MyDate.js"
import { ThemeModel } from "../../../models/ThemeModel.js"
let myDate = new MyDate()
let Product = new ProductModel()
let Category = new CategoryModel()
let Theme  = new ThemeModel()
Page({
    //验证字符串是否是数字
    _checkNumber:function(theObj){
      var reg = /^[0-9]+.?[0-9]*$/;
      if (reg.test(theObj)) {
          return true;
      }
      return false;
    },
    _isUpdate:function(param){
      let obj = {}
      for (var i in param) {
        if(param[i]==null || param[i]==""){
        }else{
          if(this._checkNumber(param[i])){
            obj[i]=parseFloat(param[i])//数据类型转换：字符串转换成数字
          }else{
            obj[i]=param[i].trim()//去空格处理
          }   
        }
      }
      //对表单进行检查--------》
      console.log('obj:',obj)
      return obj
    },
    //处理修改表单
    _handlerSubmit:function(evt){
      //第一步：对表单数据进行处理
      this.deformatImgs(this.data.productImages,'productImages')
      this.deformatImgs(this.data.detailImages,'detailImages')
      //获取新图片和旧图片
      let delImgs = this.differenceImgs(this.data.product.product_imgs,this.data.productImages)
      console.log('delimgs',delImgs)
      //需要上传的新图片地址
      let uploadProductImages = this.differenceImgs(this.data.productImages,this.data.product.product_imgs)
      let uploadDetailImages = this.differenceImgs(this.data.detailImages,this.data.product.detail_imgs)
      console.log('upload',uploadProductImages,uploadDetailImages)
      let productImages = this._spliceString(this.data.productImages,20,'product')
      let detailImages = this._spliceString(this.data.detailImages,20,'detail')

      this.setData({
        'product.product_imgs':productImages,
        'product.detail_imgs':detailImages
      })
      let product = this.data.product
      
      //第二步：修改数据库
      let productId = this.data.product._id
      delete product._id
      console.log('pbefore',product)
      Product.updateProduct(product,productId,res=>{
        console.log('修改数据成功',res)
      })

      //第三步：删除旧图片
      this._delImage(delImgs)

      //第四步：上传新图片
      this._uploadImages(uploadProductImages,"product")
      this._uploadImages(uploadDetailImages,"detail")
      wx.navigateBack({
        delta: 1,
      })

    },
    _delImage:function(delImgs){
      wx.cloud.deleteFile({
        fileList:delImgs,
        success:res=>{
          console.log('删除成功', res)
        }
      })
    },
    _spliceString:function(arrays,length,directory){
      let newarr = []
      console.log('array',arrays)
      arrays.forEach(element=>{
      let str = element.substr(element.length-length,element.length)
        newarr.push('/'+directory+'/'+str)
        console.log('for',str)
      })
      return newarr
    },
    _uploadImages:function(images,directory){
      images.forEach(element=>{
        let imagepath = element
        let name = imagepath.substr(imagepath.length-20,imagepath.length)
        wx.cloud.uploadFile({
          // 指定上传到的云路径
          cloudPath: directory+'/'+name,
          // 指定要上传的文件的小程序临时文件路径
          filePath: imagepath,
          // 成功回调
          success: res => {
            console.log('上传成功', res)
          },
        })
      })
    },

    /**
     * 页面的初始数据
     */
    data: {
      product:{},
      productThemes:[],
      productCategories: [],
      theme: 1,
      category: 1,
      productImages:[],//商品swipper
      detailImages:[],//商品详情
      delImages:[],//需要删除的图片
      product_name:'',
      product_stock:'',
      product_price:'',
      product_sell_price:'',
      product_tag:'',
      showButton:true,
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      this._init()
      Product.getProductById(options.product_id,res=>{
        this.setData({
          product: res.result.data.data,
          productImages: res.result.data.data.product_imgs,
          detailImages:  res.result.data.data.detail_imgs,
          category: res.result.data.data.category_type,
          theme: res.result.data.data.product_theme,
        })
      
       this.formatImgs(res.result.data.data.product_imgs,'productImages')
       this.formatImgs(res.result.data.data.detail_imgs,'detailImages')
       this.checkInput()
      })
    },
    formatImgs:function(imgs,name){
      let arr = []
      for(let i of imgs){
        arr.push({url:i})
      }
      this.setData({
        [name]:arr
      })
    },
    deformatImgs:function(imgs,name){
      let arr = []
      for(let i of imgs){
        arr.push(i.url)
      }
      this.setData({
        [name]:arr
      })
    },
    _init:function(){
      Category.getCateGory(res=>{
        let data1 = res.result.data.data
        var newArr = data1.map(function(item){
          return{
            text:item['category_name'],
            value:item['category_type']
          }
        })
        this.setData({
          productCategories: newArr
        })
      })
      Theme.getTheme(res=>{
        let data1 = res.result.data.data
        var newArr = data1.map(function(item){
          return{
            text:item['theme_name'],
            value:item['theme_type'],
          }
        })
        this.setData({
          productThemes:newArr
        })
        console.log('theme',this.data.productThemes)
      })
    },
    //文本输入校验
    onChange:function(event){
      let that = this
      let input = event.detail 
      let attribute = event.currentTarget.dataset.data
      var attribute2 = 'product.'+attribute
      this.setData({
        [attribute2]:input
      })
      //校验是否为空
      if(input == '' || input == null){
        that.setData({
          [attribute]:'输入不能为空'
        })
        that.checkInput()
      }else{
        that.setData({
          [attribute]:''
        })
        //校验格式是否错误
        switch(attribute){
            case 'product_stock':
              {
                if(!that.checkNumber(input)){
                  that.setData({
                    [attribute]:'输入必须为正整数'
                  })
                }
              }break;
            case 'product_price':
            case 'product_sell_price':
                {
                  if(!that.checkPrice(input)){
                    that.setData({
                      [attribute]:'输入必须为数字'
                    })
                  }
                }break;
            default:{
                  that.setData({
                    [attribute]:''
                  })
                }
        }
        //校验输入合法性
        that.CheckMsg(input).then(res=>{
          if(!res){
            that.setData({
              [attribute]:'内容含有违法违规内容'
            })
          }
          that.checkInput()
        })
      }
    },
    inputTag:function(e){
      this.setData({
        'product.product_tag':e.detail
      })
    },
    switchTheme:function(e){
      this.setData({
        'product.product_theme':e.detail
      })
    },
    switchCategory:function(e){
      this.setData({
        'product.category_type':e.detail
      })
    },
     //校验价格格式
     checkPrice:function(input){
      var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
      return reg.test(input)
     },
     checkNumber:function(input){
       var reg = /^[1-9]\d*$/;
       return reg.test(input)
     },
     checkInput:function(){
       if(this.data.product_name == '' && this.data.product_stock == '' && this.data.product_price == '' && this.data.product_sell_price == '' && this.data.detailImages.length > 0 && this.data.productImages.length > 0){
         this.setData({
           showButton:false
         })
       }else{
         this.setData({
           showButton:true
         })
       }
     },
    //删除图片
    delete:function(event){
      let productImages = this.data.productImages
      let index = event.detail.index
      productImages.splice(index,1)
      this.setData({
        productImages:productImages,
      })
      this.checkInput()
    },
    deleteDetail:function(event){
      let detailImages = this.data.detailImages
      let index = event.detail.index
      detailImages.splice(index,1)
      this.setData({
        detailImages:detailImages,
      })
      this.checkInput()
    },
    //求差集
    differenceImgs:function(a,b){
      let set1 = new Set(a),set2 = new Set(b);
      return [...new Set([...set1].filter(x => !set2.has(x)))];
     },
      //选择商品主图片
    afterRead(event) {
      let images = event.detail.file
      for(let i=0;i<images.length;i++){
      this.ImgCheck(images[i].path,i+1)
      }
    },
    //选择商品详情图片
    afterReadDetail(event) {
      let images = event.detail.file
      console.log('event',event)
      for(let i=0;i<images.length;i++){
        this.detailImgCheck(images[i].path,i+1)
      }
    },
    CheckMsg:function(msg){ 
      let call =  wx.cloud.callFunction({
         name:'ContentCheck',
         data: {
           $url:'MsgCheck',
           msg:msg
         }
       }).then(MsgRes=>{
         if (MsgRes.result.data.errCode == "87014") {
           return Promise.resolve(false)
         }else{
           return Promise.resolve(true)
         }
       }).then(res=>{
          return res
       })
     return call
     },
   /**
    * 
    * @param {*} filePath  图片临时存储地址
    * @param {*} number    第几张图片
    * @param {*} max       可上传的图片最大数量
    */
    ImgCheck:function(filePath,number){
      wx.showLoading({
        title: '图片加载中',
      })
       // 图片转化buffer后，调用云函数
       let that = this
       wx.getFileSystemManager().readFile({
         filePath: filePath,  
         success: res => {
          wx.cloud.callFunction({
              name: "ContentCheck",
              data: {
                $url:'ImgCheck',
                ImgBuffer: res.data,
              }
            }).then(
              imgRes => { 
                if (imgRes.result.data.errCode == "87014") {
                  wx.hideLoading({
                    complete: (res) => {},
                  })
                  wx.showToast({
                    title: "图片"+number+"含有违法违规内容",
                    icon: "none"
                  })
                } else {
                  //图片正常 
                  wx.hideLoading({
                    complete: (res) => {},
                  })
                  if (that.data.productImages.length == 0) {
                    that.setData({
                      productImages: [{url:filePath}],
                    })
                    that.checkInput()
                  } else {   
                    that.setData({
                      productImages: that.data.productImages.concat({url:filePath})
                    })
                 } 
                } 
              },
              function (error) {
                wx.hideLoading({
                  complete: (res) => {},
                })
                wx.showToast({
                  title: "失败，请重试",
                  icon: "none"
                })
           })
      } 
     }) 
    },
    detailImgCheck:function(filePath,number){
     wx.showLoading({
       title: '图片加载中',
     })
      // 图片转化buffer后，调用云函数
      let that = this
      wx.getFileSystemManager().readFile({
        filePath: filePath,  
        success: res => {
            wx.cloud.callFunction({
             name: "ContentCheck",
             data: {
               $url:'ImgCheck',
               ImgBuffer: res.data,
             }
           }).then(
             imgRes => { 
               if (imgRes.result.data.errCode == "87014") {
                 wx.hideLoading({
                   complete: (res) => {},
                 })
                 wx.showToast({
                   title: "图片"+number+"含有违法违规内容",
                   icon: "none"
                 })
               } else {
                 //图片正常 
                 wx.hideLoading({
                   complete: (res) => {},
                 })
                 if (that.data.detailImages.length == 0) {
                   that.setData({
                     detailImages: [{url:filePath}],
                   })
                   that.checkInput()
                 } else {   
                   that.setData({
                     detailImages: that.data.detailImages.concat({url:filePath})
                   })
                } 
               } 
             },
             function (error) {
               wx.hideLoading({
                 complete: (res) => {},
               })
               wx.showToast({
                 title: "失败，请重试",
                 icon: "none"
               })
               console.log("失败：" + error);
          })
     } 
    })
    
   },

})